package com.assetmanage.service.impl;

import com.assetmanage.service.MinioService;
import com.assetmanage.utils.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MinioServiceImpl implements MinioService {
    private final MinioClient minioClient;
    private final String bucketName;

    public MinioServiceImpl() {
        this.minioClient = MinioConfig.getMinioClient();
        this.bucketName = MinioConfig.getDefaultBucket();
        try {
            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("初始化MinIO服务失败", e);
        }
    }

    @Override
    public List<FileInfo> listFiles() throws Exception {
        List<FileInfo> fileList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 列出所有对象
        Iterable<Result<Item>> results = minioClient.listObjects(
            ListObjectsArgs.builder().bucket(bucketName).build()
        );

        for (Result<Item> result : results) {
            Item item = result.get();
            if (!item.isDir()) {
                // 将ZonedDateTime转换为Date
                Date lastModified = Date.from(item.lastModified().toInstant());
                FileInfo fileInfo = new FileInfo(
                    item.objectName(),
                    item.size(),
                    sdf.format(lastModified)
                );
                fileList.add(fileInfo);
            }
        }

        return fileList;
    }

    @Override
    public String uploadFile(String fileName, InputStream inputStream, String contentType) throws Exception {
        // 上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .contentType(contentType)
                .build());
        
        // 返回文件访问URL
        return getFileUrl(fileName);
    }

    @Override
    public InputStream downloadFile(String fileName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }

    @Override
    public void deleteFile(String fileName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }

    @Override
    public String getFileUrl(String fileName) throws Exception {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(fileName)
                .expiry(7, TimeUnit.DAYS)
                .build());
    }
} 